package Review;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo2_DriverManager {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet =null;
        try {
            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
             //2.获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "Wm127369#");
            //3.创建Statement对象
            statement = connection.createStatement();
            //4.定义SQL并执行SQL语句
            System.out.println("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            //接收用户输入
            String name = scanner.next();
            String sql = "select id,name,chinese,math,english from exam where name ='"+name + "'";
            statement.executeQuery(sql);
            //5.执行SQL，获取查询结果
            resultSet = statement.executeQuery(sql);
            //6.对结果进行遍历，获取结果集
            while (resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuName = resultSet.getString(2);
               float stuChinese = resultSet.getFloat(3);
                float stuMath = resultSet.getFloat(4);
                float stuEnglish = resultSet.getFloat(5);
                System.out.println(MessageFormat.format("学生编号={0},学生姓名 = {1}, 语文成绩 = {2},数学成绩 = {3},英语成绩 = {4}",stuId,
                        stuName,stuChinese,stuMath,stuEnglish));

            }
        }catch (SQLException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            //依次释放资源,关闭连接
            if (resultSet !=null){
                try {
                    resultSet.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if (statement !=null){
                try {
                    statement.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if ( connection !=null){
                try{
                    connection.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
